package com.zhieasy.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zhieasy.domain.Admin;
import com.zhieasy.domain.Student;

import java.util.Calendar;

/**
 * @author 风亦未止
 * @date 2021/11/20 19:31
 */
public class JwtUtil {
    private static String sign="$zhieasy$";

    /**
     * 生成token，学生
     * @param student
     * @return
     */
    public static String getToken(Student student){
        Calendar instance = Calendar.getInstance();
        //3天过期
        instance.add(Calendar.DATE,3);
        String token = JWT.create()
                .withClaim("studentId", student.getStudentId())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(JwtUtil.sign));
        return token;
    }

    /**
     * 生成token，管理员
     * @param admin
     * @return
     */
    public static String getTokenByAdmin(Admin admin){
        Calendar instance = Calendar.getInstance();
        //3天过期
        instance.add(Calendar.DATE,3);
        String token = JWT.create()
                .withClaim("admin", admin.getUsername())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(JwtUtil.sign));
        return token;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(JwtUtil.sign)).build().verify(token);
    }

}
